<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

abstract class Block_Admin_Grid extends Core_Block {

	protected function _prepareCollection() { return array(); }

	protected function _beforeRender() {
		$collection = $this->_prepareCollection();
		$order = $this->getCurrentOrder();
		$dir = $this->getCurrentDirection();

		if ($order) $collection->getSelect()->order($order, $dir=='asc');
		if ($toolbar = $this->getChild('toolbar'))
			$toolbar->setCollection($collection);

		$this->setData('collection', $collection);
	}
	
	public function getOrderUrl($col) {
		$query = App::get();
		$query['order'] = $col;
		$query['dir'] = 'asc';
		if ($this->getCurrentOrder()==$col) {
			$curDir = $this->getCurrentDirection();
			$query['dir'] = $curDir=='desc' ? 'asc' : 'desc';
		}
		return App::url('*/*/*', array('_query' => $query));
	}
	
	public function getCurrentOrder() {
		$cookie = App::objectSingleton('Core_Cookie');
		$order = array_val(App::get('order'), $cookie->get('order'));
		if (App::get('order'))
			$cookie->set('order', App::get('order'));
			
		if (!in_array($order, $this->getSortableColumns())) return null;
		return $order;
	}
	
	public function getCurrentDirection() {
		$cookie = App::objectSingleton('Core_Cookie');
		$dir = array_val(App::get('dir'), $cookie->get('dir'), 'asc');
		if (App::get('dir'))
			$cookie->set('dir', App::get('dir'));
		return $dir;
	}

	public function getRowUrl($id) {
		return App::url("*/*/edit", array('id' => $id) );
	}

	public function getNewUrl() {
		return App::url('*/*/add');
	}
	
	public function getClass($col) {
		$cssClass = 'not-sort';
		if ($this->getCurrentOrder()==$col) {
			$dir = $this->getCurrentDirection();
			$cssClass = 'icon-arrow-' . ($dir=='desc' ? 'down' : 'up');
		}
		return $cssClass;
	}
	
	protected function getSortableColumns() {
		return array();
	}
}